package cn.wsxiot.leetcode.utils;

import java.util.LinkedList;
import java.util.Queue;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    TreeNode(int x) {
        val = x;
    }

    public String serialize(TreeNode root) {
        if (root == null) {
            return "[]";
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        while (!queue.isEmpty()) {
            TreeNode pollNode = queue.poll();
            if (pollNode == null) {
                sb.append("null,");
            } else {
                queue.offer(pollNode.left);
                queue.offer(pollNode.right);
                sb.append(pollNode.val);
                sb.append(",");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.append("]").toString();
    }

    public TreeNode deserialize(String data) {
        if (data.length() <= 2) {
            return null;
        }
        String[] strs = data.substring(1, data.length() - 1).split(",");
        int i = 0;
        TreeNode headNode = new TreeNode(Integer.parseInt(strs[i++]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(headNode);
        while (i < strs.length) {
            TreeNode pollNode = queue.poll();
            if (pollNode == null) {
                continue;
            }
            if (i < strs.length && !"null".equals(strs[i])) {
                pollNode.left = new TreeNode(Integer.parseInt(strs[i]));
                queue.offer(pollNode.left);
            }
            i++;
            if (i < strs.length && !"null".equals(strs[i])) {
                pollNode.right = new TreeNode(Integer.parseInt(strs[i]));
                queue.offer(pollNode.right);
            }
            i++;
        }
        return headNode;
    }
}
